package com.zh.note.leetcode.graph;

/**
 * @Author: zhanghuan
 * @date: 2023/9/13 10:40
 * @description: create it
 */
public class LC_695_maxAreaOfIsland {
    public static final int[][] dir = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};

    public int maxAreaOfIsland(int[][] grid) {
        int res = 0;
        boolean[][] visited = new boolean[grid.length][grid[0].length];
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (grid[i][j] == 1) {
                    int value = dfs(grid, i, j, visited);
                    res = Math.max(res, value);
                }
            }
        }
        return res;
    }

    private int dfs(int[][] grid, int x, int y, boolean[][] visited) {
        if (visited[x][y] == true || grid[x][y] == 0) {
            return 0;
        }
        visited[x][y] = true;
        int count = grid[x][y];
        for (int i = 0; i < dir.length; i++) {
            int newX = x + dir[i][0];
            int newY = y + dir[i][1];
            if (newX < 0 || newX >= grid.length || newY < 0 || newY >= grid[0].length) {
                continue;
            }
            count += dfs(grid, newX, newY, visited);
        }
        return count;
    }
}
